/**
 * 表格公共model,
 * service后端api， url判断当前路由URL
 */
import { message } from 'antd';

const grid = (service, url, namespace) => {
  return {
    state: {
      data: [],
      total: 0,
      current: 1,
      size: 20,
      selectedRowKeys: [],
      keyword: null,
    },
    subscriptions: {
      setup({ dispatch, history }) {
          return history.listen(({ pathname, query }) => {
            //刷新时，检测包含-refresh，就执行
            if(pathname.indexOf('-refresh') > -1) {
              const paths = pathname.split('-');
              console.log(paths)
              if (paths[0] === url) {
                dispatch({ type: 'fetch', payload: { current: 1, size: 20, ...query } });
              }
            }
          });
      },
    },
    reducers: {
      fetchSuccess(state, { payload: { data, payload } }) {
          return { ...state, ...data, selectedRowKeys: [], ...payload };
      },
      onChangeSelectedRowKeys(state, { payload }) {
          return { ...state, selectedRowKeys: payload };
      },
    },
    effects: {
      *superFetch({ payload }, { call, put, select }) {
        const data = yield call(service.fetch, payload);
        if (data) {
            yield put({
                type: 'fetchSuccess',
                payload: { data, payload }
            });
        }
      },
      *remove({ payload }, { call, put, select }) {
        let data;
        if (payload instanceof Array) {
            const size = payload.length;
            for (let i = 0; i < size; i++) {
                data = yield call(service.remove, {id: payload[i]});
                if (data) {
                    message.success(`第${i + 1}条删除成功`);
                }
            }
        } else {
            data = yield call(service.remove, { id: payload.id});
        }
        if(data) {
          yield put({ type: 'fetch' });
        }
      },
      *update({ payload: params, callback }, { call, put }) {
        return yield call(service.update, params);
      },
      *create({ payload: params }, { call, put }) {
        return yield call(service.create, params);
      },
      *fetchById({ payload }, { call, put }) {
        return yield call(service.fetchById, payload);
      }
    }
  }
}

export default grid;
